import Vue from "vue"

Vue.prototype.toPage = (path, query = {}, cb) => {
	if (typeof path == "number") {
		// #ifdef H5
		const pages = getCurrentPages()
		if (pages.length > 1) {
			uni.navigateBack({
				delta: Math.abs(path),
			})
			return
		}
		history.go(path)
		// #endif
		// #ifndef H5
		uni.navigateBack({
			delta: Math.abs(path),
		})
		// #endif
		return
	}

	let type = "navigateTo"

	if (typeof query === "string") {
		type = query
		query = {}
	}
	if (typeof cb === "string") {
		type = cb
	}

	if (type === "replace") {
		type = "redirectTo"
	} else if (type === "replaceAll") {
		type = "reLaunch"
	} else if (type === "tabbar") {
		type = "switchTab"
	}

	if (type === "switchTab" && JSON.stringify(query) !== "{}") {
		uni.setStorageSync("switchTabQuery", query)
	}

	let qsString = Object.keys(query).map(key => key + "=" + query[key])
	const url = qsString.length ? path + "?" + qsString.join("&") : path

	uni[type || "navigateTo"]({
		url,
	})
}

export function makeUpZero(number, length) {
	if (number >= 10) return number + ""
	return (Array(length).join(0) + "" + number).slice(0, length)
}
/**
 * @param {Date|string|number} date 时间
 * @param {string} fmt 格式化字符串
 *  @value {string} YY|YYYY 年
 *  @value {string} M|MM 月
 *  @value {string} D|DD 日
 *  @value {string} h|hh|H|HH 时
 *  @value {string} m|mm 分
 *  @value {string} s|ss|S|SS 秒
 * @returns {string}
 */
export function formatDate(date, fmt) {
	if (typeof date === "string") {
		date = date.replace(/-/g, "/")
	} else if (typeof date === "number") {
		if (date + "" > 13) {
			date = +(date + "").substr(0, 13)
		} else if (date + "" < 13) {
			date = +makeUpZero(date, 13)
		}
	}

	const time = new Date(date)
	const year = time.getFullYear()
	const month = time.getMonth() + 1
	const day = time.getDate()
	const hour = time.getHours()
	const minute = time.getMinutes()
	const second = time.getSeconds()
	return fmt.replace(/YYYY|yyyy|YY|yy|MM|M|DD|dd|D|d|hh|h|HH|H|mm|m|ss|s|SS|S/g, function (a) {
		switch (a) {
			case "yy":
			case "YY":
				return (year + "").slice(2)
			case "yyyy":
			case "YYYY":
				return year
			case "M":
				return month
			case "MM":
				return makeUpZero(month, 2)
			case "d":
			case "D":
				return day
			case "dd":
			case "DD":
				return makeUpZero(day, 2)
			case "h":
			case "H":
				return hour
			case "hh":
			case "HH":
				return makeUpZero(hour, 2)
			case "m":
				return minute
			case "mm":
				return makeUpZero(minute, 2)
			case "s":
			case "S":
				return second
			case "ss":
			case "SS":
				return makeUpZero(second, 2)
		}
	})
}

Vue.prototype.formatDate = formatDate
